#!/bin/sh

e2e_test_install() {
  NODE_LABEL_KEY="$(random_string)"
  NODE_LABEL_VALUE="$(random_string)"

  kubectl create namespace "$CLUSTER_NAMESPACE"

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1 \
    --set-string "cluster.pods.scheduling.nodeSelector.$NODE_LABEL_KEY=$NODE_LABEL_VALUE" \
    --set-string cluster.distributedLogs.sgDistributedLogs=distributedlogs \
    --set distributedLogs.enabled=true \
    --set-string "distributedLogs.scheduling.nodeSelector.$NODE_LABEL_KEY=$NODE_LABEL_VALUE"
}

e2e_test_uninstall() {
  helm_cleanup_chart "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  k8s_async_cleanup_namespace "$CLUSTER_NAMESPACE"
}

e2e_test() {
  run_test "sgcluster has specified node selector" check_sgcluster_has_node_selector

  run_test "sgcluster's StatefulSet has specified node selector" check_sgcluster_sts_has_node_selector

  run_test "sgdistributedlogs's has specified node selector" check_sgdistributedlogs_has_node_selector

  run_test "sgdistributedlogs's StatefulSet has specified node selector" check_sgdistributedlogs_sts_has_node_selector
}

check_sgcluster_has_node_selector() {
  if [ "$(kubectl get sgcluster -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" \
    --template "{{ (index .spec.pods.scheduling.nodeSelector \"$NODE_LABEL_KEY\") }}")" \
    = "$NODE_LABEL_VALUE" ]
  then
    success "sgcluster has the configured node selector"
  else
    fail "sgcluster has not the configured node selector"
  fi
}

check_sgcluster_sts_has_node_selector() {
  echo "Waiting for sts with node selector"  
  try_function wait_until eval "$(cat << 'EOF'
[ "$(kubectl get sts -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" \
  --template "{{ (index .spec.template.spec.nodeSelector \"$NODE_LABEL_KEY\") }}")" \
  = "$NODE_LABEL_VALUE" ]
EOF
    )"
  if "$RESULT"
  then
    success "sgcluster's StatefulSet has the configured node selector"
  else
    fail "sgcluster's StatefulSet has not the configured node selector"
  fi
}

check_sgdistributedlogs_has_node_selector() {
  if [ "$(kubectl get sgdistributedlogs -n "$CLUSTER_NAMESPACE" "distributedlogs" \
    --template "{{ (index .spec.scheduling.nodeSelector \"$NODE_LABEL_KEY\") }}")" \
    = "$NODE_LABEL_VALUE" ]
  then
    success "sgdistributedlogs has the configured node selector"
  else
    fail "sgdistributedlogs has not the configured node selector"
  fi
}

check_sgdistributedlogs_sts_has_node_selector() {
  echo "Waiting for sts with node selector"  
  try_function wait_until eval "$(cat << 'EOF'
[ "$(kubectl get sts -n "$CLUSTER_NAMESPACE" "distributedlogs" \
  --template "{{ (index .spec.template.spec.nodeSelector \"$NODE_LABEL_KEY\") }}")" \
  = "$NODE_LABEL_VALUE" ]
EOF
    )"
  if "$RESULT"
  then
    success "sgdistributedlogs's StatefulSet has the configured node selector"
  else
    fail "sgdistributedlogs's StatefulSet has not the configured node selector"
  fi
}
